import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import logo from '../logo.png';

export function Home() {
  const navigate = useNavigate();
  const [isVisible, setIsVisible] = useState(false);
  const [activeDot, setActiveDot] = useState(0);
  const [typedText, setTypedText] = useState('');
  const fullText = '让AI成为您的知识管理专家';

  // 确保页面加载时滚动到顶部
  useEffect(() => {
    window.scrollTo(0, 0);
    
    // 防止浏览器记忆滚动位置
    if ('scrollRestoration' in history) {
      history.scrollRestoration = 'manual';
    }
  }, []);

  // 打字机效果
  useEffect(() => {
    setIsVisible(true);
    
    let i = 0;
    const typeTimer = setInterval(() => {
      if (i < fullText.length) {
        setTypedText(fullText.substring(0, i + 1));
        i++;
      } else {
        clearInterval(typeTimer);
      }
    }, 100);

    return () => clearInterval(typeTimer);
  }, []);

  // 背景粒子动画
  useEffect(() => {
    const dotsInterval = setInterval(() => {
      setActiveDot(prev => (prev + 1) % 5);
    }, 2000);

    return () => clearInterval(dotsInterval);
  }, []);

  // 特性卡片动画
  const fadeInUpClass = "opacity-0 translate-y-10 transition-all duration-1000";
  const fadeInUpVisibleClass = "opacity-100 translate-y-0";

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 overflow-hidden relative">
      {/* 背景动画粒子 */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        {[...Array(20)].map((_, i) => (
          <div 
            key={i}
            className={`absolute rounded-full bg-blue-400 opacity-10 
                      ${i % 5 === activeDot ? 'animate-pulse' : ''}`}
            style={{
              width: `${Math.random() * 100 + 50}px`, 
              height: `${Math.random() * 100 + 50}px`,
              left: `${Math.random() * 100}%`,
              top: `${Math.random() * 100}%`,
              animationDelay: `${Math.random() * 2}s`
            }}
          />
        ))}
      </div>

      {/* 导航栏 */}
      <nav className="fixed w-full bg-white/80 backdrop-blur-sm shadow-sm z-50">
        <div className="max-w-7xl mx-auto px-4 py-4 flex justify-between items-center">
          <div className="flex items-center gap-2">
            <img src={logo} alt="智能会话助手" className="h-8 animate-spin-slow" />
            <span className="text-xl font-bold text-gray-800">智能会话助手</span>
          </div>
          <div className="flex gap-4">
            <button className="px-4 py-1.5 text-gray-600 hover:text-gray-900 transition-colors">
              功能
            </button>
            <button className="px-4 py-1.5 text-gray-600 hover:text-gray-900 transition-colors">
              关于我们
            </button>
            <button
              onClick={() => navigate('/login')}
              className="px-6 py-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-all hover:shadow-lg hover:-translate-y-0.5"
            >
              登录/注册
            </button>
          </div>
        </div>
      </nav>

      {/* 主要内容区 */}
      <main className="pt-20">
        {/* Hero 区域 */}
        <section className="max-w-7xl mx-auto px-4 py-16 text-center relative">
          <div className={`transition-all duration-1000 ${isVisible ? 'opacity-100' : 'opacity-0'}`}>
            <h1 className="text-4xl md:text-6xl font-bold text-gray-900 mb-6">
              知识库驱动的智能会话助手
            </h1>
            <p className="text-xl text-gray-600 mb-2 h-8">
              {typedText}
              <span className="animate-blink ml-0.5">|</span>
            </p>
            <p className="text-lg text-gray-500 mb-8">
              集搜索、阅读、写作于一体的效率工具
            </p>
            <button
              onClick={() => navigate('/register')}
              className="px-8 py-3 bg-blue-600 text-white text-lg rounded-full hover:bg-blue-700 transition-all hover:scale-105 hover:shadow-xl"
            >
              立即注册
            </button>
          </div>
          
          {/* 波浪动画 */}
          <div className="absolute bottom-0 left-0 right-0 h-8 overflow-hidden">
            <div className="absolute inset-0 w-[200%] animate-wave" 
                style={{
                  backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 1200 120\' preserveAspectRatio=\'none\'%3E%3Cpath d=\'M0,0 C150,90 350,0 500,100 C650,190 850,100 1000,190 L1200,0 Z\' style=\'fill: %23f1f5f9;\'%3E%3C/path%3E%3C/svg%3E")',
                  backgroundRepeat: 'repeat-x',
                  height: '50px'
                }}>
            </div>
          </div>
        </section>

        {/* 功能亮点区域 */}
        <section className="bg-white py-16">
          <div className="max-w-7xl mx-auto px-4">
            <h2 className="text-3xl font-bold text-center mb-12">
              <span className="bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-indigo-600">
                核心功能
              </span>
            </h2>
            <div className="grid md:grid-cols-3 gap-8">
              <div className={`transform transition-all duration-1000 delay-100 ${fadeInUpClass} ${isVisible ? fadeInUpVisibleClass : ''}`}>
                <FeatureCard
                  icon="🔍"
                  title="智能搜索"
                  description="快速准确地从海量知识库中检索信息"
                />
              </div>
              <div className={`transform transition-all duration-1000 delay-300 ${fadeInUpClass} ${isVisible ? fadeInUpVisibleClass : ''}`}>
                <FeatureCard
                  icon="📚"
                  title="深度阅读"
                  description="智能分析文本，提取关键信息"
                />
              </div>
              <div className={`transform transition-all duration-1000 delay-500 ${fadeInUpClass} ${isVisible ? fadeInUpVisibleClass : ''}`}>
                <FeatureCard
                  icon="✍️"
                  title="高效创作"
                  description="AI辅助写作，提升内容输出效率"
                />
              </div>
            </div>
          </div>
        </section>

        {/* 使用场景展示 */}
        <section className="py-16 bg-gray-50">
          <div className="max-w-7xl mx-auto px-4">
            <h2 className="text-3xl font-bold text-center mb-12">适用场景</h2>
            <div className="flex flex-wrap justify-center">
              <div className="grid md:grid-cols-4 gap-6 w-full max-w-4xl">
                {[
                  {title: "写周报", description: "智能总结工作内容，一键生成专业周报"},
                  {title: "代码开发", description: "AI辅助编程，解决技术难题"},
                  {title: "行程规划", description: "智能规划行程，合理安排时间"},
                  {title: "文档处理", description: "快速处理文档，提取关键信息"}
                ].map((scene, index) => (
                  <div key={index} className={`transform transition-all duration-700 delay-${index * 200} hover:scale-105`}>
                    <SceneCard
                      title={scene.title}
                      description={scene.description}
                    />
                  </div>
                ))}
              </div>
            </div>
            
            {/* 对话示例 */}
            <div className="mt-20 max-w-2xl mx-auto">
              <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100">
                <div className="bg-blue-600 text-white p-4">
                  <h3 className="text-xl font-medium">示例对话</h3>
                </div>
                <div className="p-4 space-y-4">
                  <ChatBubble 
                    sender="user" 
                    message="帮我分析这份季度销售报告的主要趋势" 
                    delay={0}
                  />
                  <ChatBubble 
                    sender="ai" 
                    message="根据您的销售报告，我发现以下三个主要趋势：1. 电子产品销售同比增长15%，成为增长最快的品类；2. 华南地区销售额环比下降8%，需要关注原因；3. 线上渠道贡献率首次超过50%，建议加强线上营销策略。" 
                    delay={1000}
                  />
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* 信任背书 */}
        <section className="bg-white py-16">
          <div className="max-w-7xl mx-auto px-4">
            <h2 className="text-3xl font-bold text-center mb-12">用户信任</h2>
            <div className="flex flex-wrap justify-center gap-8 mb-12">
              {[
                //{number: "10000+", label: "活跃用户"},
                {number: "98%", label: "用户满意度"},
                {number: "24/7", label: "在线服务"}
              ].map((stat, index) => (
                <CountUp 
                  key={index} 
                  value={stat.number} 
                  label={stat.label} 
                />
              ))}
            </div>
            
            {/* 合作伙伴 */}
            <div className="mt-16">
              <h3 className="text-xl font-medium text-center mb-8">合作伙伴</h3>
              <div className="flex flex-wrap justify-center gap-8 opacity-60">
                {[...Array(5)].map((_, i) => (
                  <div key={i} className="w-24 h-12 bg-gray-200 rounded animate-pulse"></div>
                ))}
              </div>
            </div>
            
            <div className="text-center text-gray-600 mt-12 border-t border-gray-100 pt-8">
              <p className="flex items-center justify-center gap-2">
                <span className="inline-block w-2 h-2 bg-green-500 rounded-full"></span>
                安全可靠 · 隐私保护 · 专业支持
              </p>
            </div>
          </div>
        </section>
      </main>

      {/* 页脚 */}
      <footer className="bg-gray-900 text-white py-8">
        <div className="max-w-7xl mx-auto px-4 text-center">
          <div className="flex justify-center mb-4">
            <img src={logo} alt="智能会话助手" className="h-6 mr-2" />
            <p className="font-medium">智能会话助手</p>
          </div>
          <p className="text-gray-400 text-sm">© 2024 智能会话助手. All rights reserved.</p>
        </div>
      </footer>
    </div>
  );
}

// 功能特性卡片组件
function FeatureCard({ icon, title, description }: { icon: string; title: string; description: string }) {
  return (
    <div className="p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300 hover:-translate-y-1 h-full border border-gray-100">
      <div className="text-4xl mb-4 transform transition-transform hover:scale-110">{icon}</div>
      <h3 className="text-xl font-bold mb-2 text-gray-800">{title}</h3>
      <p className="text-gray-600">{description}</p>
    </div>
  );
}

// 场景展示卡片组件
function SceneCard({ title, description }: { title: string; description: string }) {
  return (
    <div className="p-6 bg-white rounded-xl shadow-sm hover:shadow-lg transition-all duration-300 h-full border border-gray-100">
      <h3 className="text-lg font-bold mb-2 text-gray-800">{title}</h3>
      <p className="text-gray-600 text-sm">{description}</p>
    </div>
  );
}

// 对话气泡组件
function ChatBubble({ sender, message, delay = 0 }: { sender: 'user' | 'ai', message: string, delay?: number }) {
  const [visible, setVisible] = useState(false);
  
  useEffect(() => {
    const timer = setTimeout(() => setVisible(true), delay);
    return () => clearTimeout(timer);
  }, [delay]);
  
  return (
    <div className={`flex ${sender === 'user' ? 'justify-end' : 'justify-start'} transition-opacity duration-500 ${visible ? 'opacity-100' : 'opacity-0'}`}>
      <div className={`max-w-[80%] rounded-xl p-3 ${
        sender === 'user' 
          ? 'bg-blue-600 text-white rounded-tr-none' 
          : 'bg-gray-100 text-gray-800 rounded-tl-none'
      }`}>
        {message}
      </div>
    </div>
  );
}

// 数字增长动画组件
function CountUp({ value, label }: { value: string, label: string }) {
  const [count, setCount] = useState(0);
  const [inView, setInView] = useState(false);
  
  // 分离数字和符号
  const numericPart = value.match(/\d+/)?.[0] || "0";
  const suffix = value.replace(numericPart, ""); // 提取符号部分（如 "+" 或 "%"）
  const targetValue = parseInt(numericPart);
  
  useEffect(() => {
    if (!inView) {
      const timer = setTimeout(() => setInView(true), 500);
      return () => clearTimeout(timer);
    }
    
    if (inView) {
      let startTimestamp: number;
      const duration = 1500;
      
      const step = (timestamp: number) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        setCount(Math.floor(progress * targetValue));
        
        if (progress < 1) {
          window.requestAnimationFrame(step);
        }
      };
      
      window.requestAnimationFrame(step);
    }
  }, [inView, targetValue]);
  
  return (
    <div className={`text-center transition-all duration-1000 ${inView ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-10'}`}>
      <div className="text-3xl font-bold text-blue-600">
        {/* 显示数字和符号 */}
        {count}{suffix}
      </div>
      <div className="text-gray-600">{label}</div>
    </div>
  );
} 